import axios from 'axios'

const API_URL = '/api/v1'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  timeout: 10000
})

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    console.log(`发送请求: ${config.method.toUpperCase()} ${config.url}`, config.data || {})
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  response => {
    console.log(`响应数据:`, response.data)
    return response
  },
  error => {
    console.error('响应错误:', error.response || error)
    return Promise.reject(error)
  }
)

export const taskApi = {
  async getTasks() {
    try {
      return await apiClient.get('/tasks/')
    } catch (error) {
      console.error('获取任务列表失败:', error)
      throw error
    }
  },

  async getTask(id) {
    try {
      return await apiClient.get(`/tasks/${id}/`)
    } catch (error) {
      console.error(`获取任务 ${id} 失败:`, error)
      throw error
    }
  },

  async createTask(task) {
    try {
      return await apiClient.post('/tasks/', task)
    } catch (error) {
      console.error('创建任务失败:', error)
      throw error
    }
  },

  async updateTask(id, task) {
    try {
      return await apiClient.put(`/tasks/${id}/`, task)
    } catch (error) {
      console.error(`更新任务 ${id} 失败:`, error)
      throw error
    }
  },

  async deleteTask(id) {
    try {
      return await apiClient.delete(`/tasks/${id}/`)
    } catch (error) {
      console.error(`删除任务 ${id} 失败:`, error)
      throw error
    }
  }
} 